//
//  RHLocalStatisticsVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/3/27.
//  本地监控 统计

#import "RHLocalStatisticsVC.h"
#import "RHLocalStatisticsCell.h"
#import "RHLocalLoadChartCell.h"
#import "CBLECenterMnger.h"
#import "RHBleCmdData.h"
#import "CBLEDataParse.h"
#import "RHBleCmdManager.h"
#import "SYChartTool.h"
#import "DevChartParamsModel.h"
#import "DevChartModel.h"
#import "RHCustomTimer.h"

@interface RHLocalStatisticsVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

//当前曲线数据
@property (nonatomic ,strong) NSMutableDictionary *lineDic;

//双曲线模型
@property (nonatomic ,strong) DevChartParamsModel *chartParamsModel;

@property (nonatomic ,strong) NSTimer *timer;
//双曲线数据
@property (nonatomic ,strong) NSMutableArray *chartDataArr;
@end

@implementation RHLocalStatisticsVC


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    [self setupUI];
    //定时读取曲线时不显示loading
    [ProgressHUDManage shareObject].showLoadingTips = NO;
    [self createCmd];
    [self getDeviceInfo];
   
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [ProgressHUDManage shareObject].showLoadingTips = NO;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self startReadDeviceInfo];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [ProgressHUDManage shareObject].showLoadingTips = YES;
    [self stopReadDeviceInfo];
}

-(void)createCmd
{
    NSArray *cmdArr = @[@{
        @"field":@"Ems_PvPwr",
        @"regAddr":@(200),
        @"bitWidth":@(16),
        @"ratio":@"0.1",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Ems_GridPwr",
        @"regAddr":@(203),
        @"bitWidth":@(16),
        @"dataType":@"signed",
        @"ratio":@"0.1",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Ems_LoadPwr",
        @"regAddr":@(204),
        @"bitWidth":@(16),
        @"ratio":@"0.1",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Ems_BatPwr",
        @"regAddr":@(205),
        @"bitWidth":@(16),
        @"dataType":@"signed",
        @"ratio":@"0.1",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Emu_SOC",
        @"regAddr":@(6215),
        @"bitWidth":@(16),
        @"ratio":@"0.1",
        @"cmdType":@(LocalSettingType_EMU)
    },@{
        @"field":@"Emu_TV",
        @"regAddr":@(6201),
        @"bitWidth":@(32),
        @"ratio":@"0.001",
        @"cmdType":@(LocalSettingType_EMU)
    },@{
        @"field":@"Emu_Cur",
        @"regAddr":@(6214),
        @"bitWidth":@(16),
        @"dataType":@"signed",
        @"ratio":@"0.1",
        @"cmdType":@(LocalSettingType_EMU)
    }];
    NSMutableArray *mtbArr = [NSMutableArray array];
    [cmdArr enumerateObjectsUsingBlock:^(NSDictionary  *_Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
        RHLocalSettingModel *settingModel = [RHLocalSettingModel yy_modelWithJSON:dic];
        [mtbArr addObject:settingModel];
        [self.lineDic setObject:@"0" forKey:settingModel.field];
    }];
    self.cmdArray = mtbArr.copy;
}

-(void)startReadDeviceInfo
{
    [self.timer invalidate];
    self.timer = nil;
    self.timer = [RHCustomTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(getDeviceInfo) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
    [self getDeviceInfo];
}
-(void)stopReadDeviceInfo{
    [self.timer invalidate];
    self.timer = nil;
}

-(void)getDeviceInfo
{
    if ([CBLECenterMnger shareMnger].curPheral == nil) {
        [ProgressHUDManage showInfo:@"蓝牙已断开!".rh_localized];
        [self.timer invalidate];
        self.timer = nil;
        [self.tableView endHeaderRefresh];
        return;
    }
    [[RHBleCmdManager shareMnger] readDeviceInfoFromBle:self.cmdArray];
}


-(void)receiveDeviceMsg:(NSNotification*)no
{
    NSDictionary *dic = [no object];
    if(dic.allKeys.count==0)return;
    if(!self.recieveMsg)return;

    NSLog(@"------>收到设备信息:%@",dic);
  
            
   
    [self.cmdArray enumerateObjectsUsingBlock:^(RHLocalSettingModel * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) {
        if(obj.regAddr == [dic[CMD_ADDRESS] integerValue]){
            
            NSData *data = dic[CMD_ADDRESS_VALUE];
            NSString *parse_content = [CBLEDataParse parseData:data settingModel:obj];
            NSLog(@"---->%@ = %@",obj.field,parse_content);
            
            [self.dataDic setObject:parse_content forKey:obj.field];
            [self.lineDic setObject:[NSString stringWithFormat:@"%@",parse_content] forKey:obj.field];
          
            NSLog(@"---->曲线数据:%@",self.lineDic);
        }
           
    }];
    
   
   
    
}

//数据左移
-(void)shiftChartData:(NSDictionary *)dic
{
    if(self.chartDataArr.count>=10){
        [self.chartDataArr removeObjectAtIndex:0];
        [self.chartDataArr addObject:dic];
    }else{
        //填充10个数据
        
        NSInteger timeInterval = [[NSDate date]timeIntervalSince1970]*1000;
        NSString *timeStr = [NSString stringWithFormat:@"%ld",timeInterval];
        for (int i = 0; i < 10; i++) {
            NSMutableDictionary *mtbDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            [mtbDic setObject:timeStr forKey:@"time"];
            [mtbDic setObject:@"HH:mm:ss" forKey:@"timeFormat"];//电芯电压X时间定制格式,展示秒数
            [_chartDataArr addObject:mtbDic];
        }
    }
    [self.chartParamsModel.chartList enumerateObjectsUsingBlock:^(DevChartModel*  _Nonnull chartModel, NSUInteger idx, BOOL * _Nonnull stop) {
        chartModel.allDataArray = self.chartDataArr;
    }];
    
    
}

-(void)sendCmdFinish
{
    if (!self.recieveMsg) {
        return;
    }
    //读取完全部数据点,刷新曲线
    //赋值曲线
    NSTimeInterval timeInteval = [[NSDate date]timeIntervalSince1970]*1000;
    [self.lineDic setObject:[NSString stringWithFormat:@"%ld",(NSInteger)timeInteval] forKey:@"time"];
    [self.lineDic setObject:@"HH:mm:ss" forKey:@"timeFormat"];//电芯电压X时间定制格式,展示秒数
    [self shiftChartData:self.lineDic.mutableCopy];
    [self updateVisibleCell];
    [self.tableView endHeaderRefresh];
}

//为了兼容ios 12  iphone 6机型 tableview滚动到底部时刷新talbeView会跳动的问题, 暂时不用reloadData
-(void)updateVisibleCell
{
    
    for (UITableViewCell *cell in self.tableView.visibleCells) {
        if([cell isKindOfClass:[RHLocalStatisticsCell class]]){
            RHLocalStatisticsCell *cell_1 = (RHLocalStatisticsCell*)cell;
            cell_1.bleDataDic = self.dataDic;
        }
        
        if([cell isKindOfClass:[RHLocalLoadChartCell class]]){
            RHLocalLoadChartCell *cell_2 = (RHLocalLoadChartCell*)cell;
            [cell_2 setTopChartModel:[self.chartParamsModel.chartList firstObject] bottomChartModel:[self.chartParamsModel.chartList lastObject]];
        }
    }
}

- (void)setupUI{
    kWeakSelf;
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_ACK,receiveDeviceMsg:);
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_FINISH,sendCmdFinish);
    NSDictionary *dict = [SYChartTool readLocalJsonFileWithName:@"Local_DeviceBattery"];
    self.chartParamsModel = [DevChartParamsModel yy_modelWithDictionary:dict];
//    self.chartModel = [paramsModel.chartList firstObject];
//    NSInteger timeInterval = [[NSDate date]timeIntervalSince1970];
//    self.chartModel.curTime = [NSString stringWithFormat:@"%ld",timeInterval];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = CFTabViewBgColor;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHLocalStatisticsCell class] forCellReuseIdentifier:@"RHLocalStatisticsCell_top"];
    [_tableView registerClass:[RHLocalStatisticsCell class] forCellReuseIdentifier:@"RHLocalStatisticsCell_bottom"];
    [_tableView registerClass:[RHLocalLoadChartCell class] forCellReuseIdentifier:@"RHLocalLoadChartCell"];
    
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [_tableView addHeaderRefresh:^{
        [weakSelf getDeviceInfo];
    }];
    
    _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    if (@available(iOS 13.0, *)) {
        _tableView.automaticallyAdjustsScrollIndicatorInsets = NO;
    }
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 1){
        return 40;
    }
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section == 1){
        UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 40)];;
        headView.backgroundColor = CFTabViewBgColor;
        UILabel *titleLab = [[QMUILabel alloc]init];
        titleLab.font = kBOLDSYSTEMFONT(16);
        titleLab.textColor = kColorRGB(0, 0, 0);
        titleLab.textAlignment = NSTextAlignmentLeft;
        titleLab.text = @"数据曲线".rh_localized;
        [headView addSubview:titleLab];
        
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(headView).offset(15);
            make.bottom.mas_offset(-10);
         }];
        return headView;
    }
    
    
   return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 0){
        RHLocalStatisticsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHLocalStatisticsCell_top"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.bleDataDic = self.dataDic;
        return cell;
    }else if(indexPath.section == 1){
        //数据曲线
        RHLocalLoadChartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHLocalLoadChartCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setTopChartModel:[self.chartParamsModel.chartList firstObject] bottomChartModel:[self.chartParamsModel.chartList lastObject]];
        return cell;
    }else if(indexPath.section == 2){
        kWeakSelf;
        //负载 电池 电网 光伏 功率
        RHLocalStatisticsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHLocalStatisticsCell_bottom"];
        cell.bleDataDic = self.dataDic;
        return cell;
    }
    return [UITableViewCell new];;
}



#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}

-(NSMutableDictionary *)lineDic
{
    if(!_lineDic){
        _lineDic = [NSMutableDictionary dictionary];
    }
    return  _lineDic;
}

-(NSMutableArray *)chartDataArr
{
    if(!_chartDataArr){
        _chartDataArr = [NSMutableArray array];
    }
    return  _chartDataArr;
}

- (void)dealloc
{
    [[RHBleCmdManager shareMnger] removeAllCommand];
    [self.timer invalidate];
    self.timer = nil;
}

@end
